class Publish {
  constructor() {
    this.topics = {};
  }

  // 订阅主题
  subscribe(event, callback) {
    if (!this.topics[event]) {
      this.topics[event] = [];
    }
    this.topics[event].push(callback);
  }

  // 取消订阅
  unSubscribe(event, callback) {
    if (this.topics[event]) {
      this.topics[event] = this.topics[event].filter((cd) => cd !== callback);
      if (this.topics[event].length === 0) {
        delete this.topics[event];
      }
    }
  }

  // 发布
  publish(event, data) {
    if (this.topics[event]) {
      this.topics[event].forEach((callback) => {
        callback(data);
      });
    }
  }
}

export { Publish };
